package com.huidz.calendar.activity;

import android.Manifest;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.huidz.calendar.MainActivity;
import com.huidz.calendar.R;
import com.huidz.calendar.model.JsonModel;
import com.huidz.calendar.model.ShareModel;
import com.huidz.calendar.model.XingZuoModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.TianGanDizhiShengXiao;
import com.huidz.calendar.util.Url;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LunchActivity extends AppCompatActivity implements View.OnClickListener {

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lunch);
        inti();
        Apiutils.getGeoPointBystr(LunchActivity.this, "重庆市江北区");
    }

    private TextView two, four, nit, shis;
    private boolean login_ = true;

    /**
     * 初始化加载调用方法
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void inti() {
        if (Url.QIDONGNUM.equals("")) {
            LayoutInflater inflater = LayoutInflater.from(this);
            View layout = inflater.inflate(R.layout.popupwindow_yinsiquanxian, null);
            two = layout.findViewById(R.id.two);
            two.setOnClickListener(this);
            four = layout.findViewById(R.id.four);
            four.setOnClickListener(this);
            nit = layout.findViewById(R.id.nit);
            nit.setOnClickListener(this);
            shis = layout.findViewById(R.id.shi);
            shis.setOnClickListener(this);
            new AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setTitle("用户协议和隐私政策")
                    .setView(layout)
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (login_) {
                                Intent intent = new Intent(LunchActivity.this, MainActivity.class);
                                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LunchActivity.this).toBundle());
                                LunchActivity.this.finish();
                            }
                        }
                    })
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            onBackPressed();
                        }
                    })
                    .show();
        } else {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    Intent intent = new Intent(LunchActivity.this, MainActivity.class);
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LunchActivity.this).toBundle());
                    LunchActivity.this.finish();
                }
            }, 3000);
        }
        get();
        createDB(LunchActivity.this, Apiutils.DB_NAME);
        Calendar selectedDate = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        String datetime = simpleDateFormat.format(date);
        int y = Integer.parseInt(datetime.substring(0, 4));
        TianGanDizhiShengXiao.getTGDZName(y);
        try {
            shi = Apiutils.dateToStamp(datetime) + "";
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        Apiutils.getSyn(Apiutils.GET_ALMANACURL + "key=" + Apiutils.GET_ALMANACAPIKEY + "&date=" + shi.substring(0,10));
        Gson gson = new Gson();
        jsonModel = gson.fromJson(Apiutils.JSONCODE,
                JsonModel.class);
        colorid = Apiutils.selectcolor(selectedDate.get(Calendar.HOUR_OF_DAY));

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        List<String> providers = locationManager.getProviders(true);
        Criteria criteria = new Criteria();
        criteria.setAltitudeRequired(true);//设置是否可以定位海拔,如果设置定位海拔，返回一定是gps
        String bestProvider = locationManager.getBestProvider(criteria, false);
        myLocationListener = new MyLocationListener();
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            return;
        }
        locationManager.requestLocationUpdates("network", 0, 0, myLocationListener);

    }


    public static String shi;
    public static int colorid;
    public static JsonModel jsonModel;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            LunchActivity.this.finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void createDB(Context context, String dbname) {
        File file = new File(getFilesDir(), dbname);
        if (!file.exists()) {
            AssetManager assets = getAssets();
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                is = assets.open(dbname);
                fos = new FileOutputStream(file);
                byte[] b = new byte[1024];
                int len = -1;
                while ((len = is.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Apiutils.DB_LOCTION = context.getDatabasePath(dbname).getPath();
    }

    public static LocationManager locationManager;
    public static MyLocationListener myLocationListener;
    public static String latLongString;


    public class MyLocationListener implements LocationListener {

        //当定位位置改变的调用的方法
        //Location : 当前的位置
        @Override
        public void onLocationChanged(Location location) {
            float accuracy = location.getAccuracy();//获取精确位置
            double altitude = location.getAltitude();//获取海拔
            final double latitude = location.getLatitude();//获取纬度，平行
            final double longitude = location.getLongitude();//获取经度，垂直

            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<Address> addsList = null;
                    Geocoder geocoder = new Geocoder(LunchActivity.this);
                    try {
                        addsList = geocoder.getFromLocation(latitude, longitude, 10);//得到的位置可能有多个当前只取其中一个
                        StringBuilder sb = new StringBuilder();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (addsList != null && addsList.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        if (addsList.size() > 0) {
                            Address address = addsList.get(0);
                            for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                                sb.append(address.getAddressLine(i)).append("\n");

                            sb.append(address.getLocality()).append("\n");
                            sb.append(address.getPostalCode()).append("\n");
                            sb.append(address.getCountryName());
                            Url.latitude = latitude + "";
                            Url.longitude = longitude + "";
                        }
//                        for (int i = 0; i < addsList.size(); i++) {
//                            final Address ads = addsList.get(i);
//                            latLongString = ads.getLocality();//拿到城市
//                            Apiutils.SetLog("ads:" +addsList.get(i) + ",ads1=" + ads.getThoroughfare() + ",ads2=" + latLongString);
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
////                                    locationChange.setText(latLongString + ads.getAddressLine(0) + ads.getAddressLine(1));
//                                    Url.ADDRESSCITY = latLongString;
//                                    Url.ADDRESSCITYS = ads.getAddressLine(0);
//
//                                }
//                            });
//                        }
                    }
                }
            }).start();
        }

        //当定位状态发生改变的时候调用的方式
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        //当定位可用的时候调用的方法
        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        //当定位不可用的时候调用的方法
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        locationManager.removeUpdates(myLocationListener);//关闭gps,但是高版本中规定打开和关闭gps必须由用户自己主观的去实现，代码已经不允许进行操作
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.two:
                Intent yhxy = new Intent(LunchActivity.this, FuWuTiaoKuanActivity.class);
                yhxy.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10000.html");
                yhxy.putExtra("title", "用户协议");
                startActivity(yhxy);
                break;
            case R.id.four:
                Intent yszc = new Intent(LunchActivity.this, FuWuTiaoKuanActivity.class);
                yszc.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10001.html");
                yszc.putExtra("title", "隐私政策");
                startActivity(yszc);
                break;
            case R.id.nit:
                Intent yhxy1 = new Intent(LunchActivity.this, FuWuTiaoKuanActivity.class);
                yhxy1.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10000.html");
                yhxy1.putExtra("title", "用户协议");
                startActivity(yhxy1);
                break;
            case R.id.shi:
                Intent yszc1 = new Intent(LunchActivity.this, FuWuTiaoKuanActivity.class);
                yszc1.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10001.html");
                yszc1.putExtra("title", "隐私政策");
                startActivity(yszc1);
                break;
        }
    }

    public void get() {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.SHARE).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gethots.sendMessage(message);
                } catch (Exception e) {
                    Apiutils.SetLog(e.toString() + "");
                    e.printStackTrace();
                }
            }
        });
    }

    public Handler gethots = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        ShareModel shareModel = gson.fromJson(msg.obj.toString(),
                                ShareModel.class);
                        Url.fenxiang_des = shareModel.getData().getDes();
                        Url.fenxiang_image = shareModel.getData().getImage();
                        Url.fenxiang_shareapp = shareModel.getData().getShareapp();
                        Url.fenxiang_title = shareModel.getData().getTitle();
                        Url.fenxiang_url2 = shareModel.getData().getUrl2();
                    }
                }
            } catch (
                    Exception e) {
                Apiutils.SetLog(e.toString() + "");
                e.printStackTrace();
            }
        }
    };

}
